import { saveTpl } from "@/api/service/template/template";
import { stageConfig } from "@/views/paint/modules/data/stage";

export const previewImageSrc = ref();

function updateIdInUrl(id: string): void {
  // 解析当前URL的hash部分
  let hash = window.location.hash;

  // 如果没有hash部分，初始化
  if (!hash) {
    hash = "#/";
  }

  // 分离路径和参数
  const [path, query = ""] = hash.split("?");

  // 解析现有参数
  const params = new URLSearchParams(query);

  // 设置或更新id参数（不会重复添加）
  params.set("id", id);

  // 重新组合hash部分
  const newHash = `${path}?${params.toString()}`;

  // 更新URL而不刷新页面
  history.replaceState(null, "", newHash);
}

/**
 * @description: 下发保存
 */
export const send = async (
  immediately = false,
  templateId?: string
): Promise<string | undefined> => {
  const params = {
    stage: {
      ...stageConfig.value,
      templateId: `${templateId}`
    },
    templateList: [],
    lcd: stageConfig.value.lcd
  };

  const result = await saveTpl(params, immediately);
  if (result.code === 200) {
    const id = result.data.templateId || result.data.componentId;
    stageConfig.value.id = id;
    return id;
  }
};
